package com.itheima.reggie.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.FindOrdersDto;
import com.itheima.reggie.dto.OrdersDto;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.mapper.OrderMapper;
import com.itheima.reggie.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@Service
@Slf4j
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Orders> implements OrderService {

    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private AddressBookService addressBookService;

    @Autowired
    private UserService userService;

    @Autowired
    private OrderDetailService orderDetailService;

    /**
     * 下单
     * @param orders
     */
    @Override
    public void submit(Orders orders) {

        //A. 获得当前用户id
        Long userId = BaseContext.getCurrentId();

        //查询当前用户的购物车数据
        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ShoppingCart::getUserId,userId);
        List<ShoppingCart> shoppingCarts = shoppingCartService.list(wrapper);
        //数据校验,保证逻辑完整
        if(shoppingCarts == null || shoppingCarts.size() == 0){
            throw new CustomException("购物车为空，不能下单");
        }

        //B. 根据当前登录用户id, 查询用户数据
        User user = userService.getById(userId);

        //C. 根据地址ID, 查询地址数据
        Long addressBookId = orders.getAddressBookId();
        AddressBook addressBook = addressBookService.getById(addressBookId);
        //数据校验,保证逻辑完整
        if(addressBook == null){
            throw new CustomException("用户地址信息有误，不能下单");
        }

        //TODO 雪花算法相关API
        long orderId = IdWorker.getId();//订单号

        //TODO 原子性计算,在高并发场景保证计算准确性
        AtomicInteger amount = new AtomicInteger(0);

        //组装订单明细信息
        List<OrderDetail> orderDetails = shoppingCarts.stream().map((item) -> {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(orderId);
            orderDetail.setNumber(item.getNumber());
            orderDetail.setDishFlavor(item.getDishFlavor());
            orderDetail.setDishId(item.getDishId());
            orderDetail.setSetmealId(item.getSetmealId());
            orderDetail.setName(item.getName());
            orderDetail.setImage(item.getImage());
            orderDetail.setAmount(item.getAmount());
            amount.addAndGet(item.getAmount().multiply(new BigDecimal(item.getNumber())).intValue());
            return orderDetail;
        }).collect(Collectors.toList());

        //组装订单数据
        orders.setId(orderId);
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setStatus(2);
        orders.setAmount(new BigDecimal(amount.get()));//总金额
        orders.setUserId(userId);
        orders.setNumber(String.valueOf(orderId));
        orders.setUserName(user.getName());
        orders.setConsignee(addressBook.getConsignee());
        orders.setPhone(addressBook.getPhone());
        orders.setAddress((addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
                + (addressBook.getCityName() == null ? "" : addressBook.getCityName())
                + (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
                + (addressBook.getDetail() == null ? "" : addressBook.getDetail()));

        //向订单表插入数据，一条数据
        this.save(orders);

        //向订单明细表插入数据，多条数据
        orderDetailService.saveBatch(orderDetails);

        //清空购物车数据
        shoppingCartService.remove(wrapper);

    }

    /**
     * 查看历史(最新)订单 --前台
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public IPage<OrdersDto> getOrders(Integer page, Integer pageSize) {

        //1.获取用户id
        Long userId = BaseContext.getCurrentId();

        //2.查询用户订单
        IPage<Orders> iPage = new Page<>(page,pageSize);
        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Orders::getUserId,userId);
        wrapper.orderByDesc(Orders::getCheckoutTime);
        IPage<Orders> ordersIPage = this.page(iPage, wrapper);

        //3.查询订单明细
        List<Orders> ordersList = ordersIPage.getRecords();
        List<OrdersDto> ordersDtos = JSON.parseArray(JSON.toJSONString(ordersList), OrdersDto.class);
        ordersDtos = ordersDtos.stream().map(c->{
            LambdaQueryWrapper<OrderDetail> wrapper1 = new LambdaQueryWrapper<>();
            wrapper1.eq(OrderDetail::getOrderId,c.getId());
            List<OrderDetail> orderDetails = orderDetailService.list(wrapper1);
            c.setOrderDetails(orderDetails);
            return c;
        }).collect(Collectors.toList());

        //4.封装为IPage<OrdersDto>对象
        IPage<OrdersDto> ordersDtoIPage = new Page<>();
        ordersDtoIPage.setRecords(ordersDtos);
        ordersDtoIPage.setTotal(ordersIPage.getTotal());
        ordersDtoIPage.setCurrent(ordersIPage.getCurrent());
        ordersDtoIPage.setPages(ordersIPage.getPages());
        ordersDtoIPage.setSize(ordersIPage.getSize());
        return ordersDtoIPage;
    }

    /**
     * 订单查询 -- 后台
     * @param findOrdersDto -- 封装查询条件
     * @return
     */
    @Override
    public IPage<OrdersDto> findByPage(FindOrdersDto findOrdersDto) {

        //1.接收查询参数
        long ordreId = findOrdersDto.getNumber();
        String beginTime = findOrdersDto.getBeginTime();
        String endTime = findOrdersDto.getEndTime();

        //2.查询订单
        IPage<Orders> iPage = new Page<>(findOrdersDto.getPage(),findOrdersDto.getPageSize());
        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();
        if(ordreId != 0){
            wrapper.eq(Orders::getId,ordreId);
        }
        if(beginTime != null && endTime != null){
            wrapper.between(Orders::getOrderTime,beginTime,endTime);
        }
        wrapper.orderByDesc(Orders::getOrderTime);
        IPage<Orders> ordersIPage = this.page(iPage, wrapper);

        //3.查询订单明细 -- 这里不需要查询
        List<Orders> ordersList = ordersIPage.getRecords();
        List<OrdersDto> ordersDtos = JSON.parseArray(JSON.toJSONString(ordersList), OrdersDto.class);
        ordersDtos = ordersDtos.stream().map(c->{
            LambdaQueryWrapper<OrderDetail> wrapper1 = new LambdaQueryWrapper<>();
            wrapper1.eq(OrderDetail::getOrderId,c.getId());
            List<OrderDetail> orderDetails = orderDetailService.list(wrapper1);
            c.setOrderDetails(orderDetails);
            return c;
        }).collect(Collectors.toList());

        //4.封装为IPage<OrdersDto>对象
        IPage<OrdersDto> ordersDtoIPage = new Page<>();
        ordersDtoIPage.setRecords(ordersDtos);
        ordersDtoIPage.setTotal(ordersIPage.getTotal());
        ordersDtoIPage.setCurrent(ordersIPage.getCurrent());
        ordersDtoIPage.setPages(ordersIPage.getPages());
        ordersDtoIPage.setSize(ordersIPage.getSize());
        return ordersDtoIPage;
    }

    /**
     * 后台订单派送
     * @param orders
     */
    @Override
    public void updateStatus(Orders orders) {
        LambdaUpdateWrapper<Orders> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(Orders::getId,orders.getId());
        wrapper.set(Orders::getStatus,orders.getStatus());
        this.update(orders,wrapper);
    }

    /**
     * 再来一单
     * @param orders
     */
    @Override
    public void again(Orders orders) {

        Long userId = BaseContext.getCurrentId();

        //1.先清空之前的购物车
        shoppingCartService.clean();

        //2.将该订单重新加入购物车
        LambdaUpdateWrapper<OrderDetail> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(OrderDetail::getOrderId,orders.getId());
        List<OrderDetail> orderDetails = orderDetailService.list(wrapper);
        for (OrderDetail orderDetail : orderDetails) {
            Long dishId = orderDetail.getDishId();
            ShoppingCart shoppingCart = new ShoppingCart();

            shoppingCart.setName(orderDetail.getName());
            shoppingCart.setImage(orderDetail.getImage());
            shoppingCart.setUserId(userId);
            shoppingCart.setNumber(orderDetail.getNumber());
            shoppingCart.setAmount(orderDetail.getAmount());

            if (null != dishId) {
                shoppingCart.setDishId(orderDetail.getDishId());
                shoppingCart.setDishFlavor(orderDetail.getDishFlavor());
            } else {
                shoppingCart.setSetmealId(orderDetail.getSetmealId());
            }
            shoppingCartService.save(shoppingCart);
        }
    }
}